package com.xishu.service;

import com.stripe.Stripe;
import com.stripe.model.PaymentIntent;
import com.xishu.config.Config;
import com.xishu.entity.order.Order;
import com.xishu.entity.payment.PaymentCheck;
import com.xishu.entity.shop.Shop;
import com.xishu.service.order.base.OrderService;
import com.xishu.util.AES;
import com.xishu.util.Tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class PaymentCheckService implements Tools {
    private static Logger logger = LoggerFactory.getLogger(PaymentCheckService.class);

    private static PaymentCheckService instance = new PaymentCheckService();
    private Config config = Config.getInstance();
    private CommonService commonService = CommonService.getInstance();

    private PaymentCheckService() {
    }

    public static PaymentCheckService getInstance() {
        return instance;
    }

    /**
     * 查询所有已经过期的支付订单
     *
     * @return
     */
    public List<PaymentCheck> queryExpireCheck() {
        PaymentCheck paymentCheck = new PaymentCheck();
        //1分钟过期
        long currentTimeMillis = System.currentTimeMillis();
        paymentCheck.setEndCreateTime(currentTimeMillis - config.getPaymentExpireTime() * 1000);
        return commonService.searchAll(paymentCheck);
    }

    /**
     * 检查每一笔支付是否已经过期了
     * 如果已经过期了，那么判断订单是否已经支付了，如果没有支付则取消
     * 如果已经过期了，订单已经支付了，那么删除该任务
     *
     * @param paymentCheck
     */
    public void validPayment(PaymentCheck paymentCheck) {
        try {
            Long shopId = paymentCheck.getShopId();
            Long orderId = paymentCheck.getOrderId();
            logger.info("check {} order {} ", shopId, orderId);
            if (orderId == null || shopId == null) {
                return;
            }

            Order orderInDb = OrderService.getInstance().findOrder(shopId, orderId);
            if (getBoolean(orderInDb.getPayed())) {
                logger.info("will delete the payment");
                //真删
                commonService.delete(paymentCheck, false);
            } else {
                //将取消支付
                logger.info("will cancel the payment");
                String paymentId = paymentCheck.getPaymentId();

                if (isEmpty(paymentId)) {
                    logger.info("will delete the payment");
                    commonService.delete(paymentCheck, false);
                    return;
                }

                synchronized (GlobalService.GLOBAL_LOCK) {
                    Shop shop = ShopService.getInstance().findShopById(shopId);
                    Stripe.apiKey = AES.decrypt(shop.getStripeSk());
                    logger.info("cancel request to stripe");
                    PaymentIntent paymentIntent = PaymentIntent.retrieve(paymentId);

                    if (!paymentIntent.getStatus().toLowerCase().contains("cancel")) {
                        paymentIntent.cancel();
                    }

                }

                logger.info("delete the payment check");
                commonService.delete(paymentCheck, false);
            }
        } catch (Exception e) {
            logger.error("e", e);
        }
    }

}
